import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 存储获取的数据列表
    list: [],
    inputValue: 'aaa',
    nextId: 5,
    viewKey: 'all'
  },
  mutations: {
    initList (state, list) {
      state.list = list
    },
    setInputValue (state, val) {
      state.inputValue = val
    },
    addItem (state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue.trim(),
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
    },
    removeItem (state, id) {
      let getId = state.list.findIndex(item => {
        return item.id === id
      })
      if (getId !== -1) {
        state.list.splice(getId, 1)
      }
    },
    changeStatus (state, param) {
      let index = state.list.findIndex((item) => {
        return item.id === param.id
      })
      if (index !== -1) {
        state.list[index].done = param.status
      }
    },
    cleanDone (state) {
      state.list = state.list.filter(item => {
        return item.done === false
      })
    },
    changeViewKey (state, key) {
      state.viewKey = key
    }
  },
  actions: {
    // 获取数据
    getList (context) {
      axios.get('./list.json').then(({ data }) => {
        // console.log(data)
        context.commit('initList', data)
      })
    }
  },
  getters: {
    unDoneLength (state) {
      let res = state.list.filter(item => {
        return item.done === false
      })
      return res.length
    },
    infoList (state) {
      if (state.viewKey === 'all') {
        return state.list
      }
      if (state.viewKey === 'undone') {
        return state.list.filter(item => !item.done)
      }
      if (state.viewKey === 'done') {
        return state.list.filter(item => item.done)
      }
      return state.list
    }
  }
})
